# coding:utf-8
import os
from datetime import date, timedelta
import set_env_path

from sqlalchemy import create_engine
from sqlalchemy.sql import text
from sqlalchemy.orm import sessionmaker

engine = create_engine(
    os.getenv('DATABASE_URL')
    or 'mysql+pymysql://root:@127.0.0.1/wph_www_prod?charset=utf8'
)
Session = sessionmaker(bind=engine)
session = Session()


def fix():
    """
    created by chenhj at 2018/6/11

    """
    calc_sql = text("""
        select count(*) as ro_cnt, sum(published_count) as published_cnt from demand
         where published_at BETWEEN :start and :end
          and published_count > 0 and area_id=710100
    """)

    update_sql = text("""
        update opc_day_stat set ro_cnt = ro_cnt - :minus1, publish_count = publish_count-:minus2
        where stat_date=:stat_date
    """)

    end_date = date(2016, 12, 25)

    today = date.today()

    while end_date < today:
        start_date = end_date
        end_date = start_date + timedelta(days=1)

        print(start_date)

        calc_res = session.execute(
            calc_sql,
            {
                'start': start_date.strftime('%s'),
                'end': end_date.strftime('%s')
            }
        ).fetchone()

        if calc_res[0] > 0:
            print(calc_res)
            session.execute(
                update_sql,
                {
                    'minus1': calc_res[0],
                    'minus2': calc_res[1] or 0,
                    'stat_date': start_date.strftime("%F")
                }
            )

    session.commit()
    session.close()


if __name__ == '__main__':
    fix()
